/**
 * Copyright (c) 2005 - 2007 FeyaSoft Corp. All Rights Reserved.
 */
package com.feyaSoft.home.web.feedback;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.web.servlet.ModelAndView;

import com.feyaSoft.home.dao.base.BaseSearchResult;
import com.feyaSoft.home.hibernate.feedback.Feedback;
import com.feyaSoft.home.services.feedback.FeedbackServiceImpl;
import com.feyaSoft.home.services.feedback.ListFeedbackInfo;
import com.feyaSoft.home.web.base.BaseController;
import com.feyaSoft.home.web.common.JsonMVCUtil;
import com.feyaSoft.plugin.util.JsonUtil;

/**
 * @author Fenqiang Zhuang
 * @Oct 10, 2007
 * 
 * This file is used to .....
 */
public class FeedbackController extends BaseController {
	// log file
	private final static Logger log = Logger
			.getLogger(FeedbackController.class);
	private FeedbackServiceImpl feedbackService;
	private String LIST_INFO = "listFeedbackInfo";

	/**
	 * Call by Ajax - here we need create a json object..
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView listResult(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		HttpSession session = request.getSession();

		// check session expired...
		ListFeedbackInfo listFeedbackInfo = new ListFeedbackInfo();
		if (session.getAttribute(LIST_INFO) != null) {
			listFeedbackInfo = (ListFeedbackInfo) session
					.getAttribute(LIST_INFO);
		}

		// check to see whether is parentId checked
		if (request.getParameter("parentId") != null) {
			String parentId = request.getParameter("parentId");
			listFeedbackInfo.setParentId(new Long(parentId));
		}

		// get paging information now...start paging
		if (request.getParameter("start") != null) {
			int start = Integer.parseInt((String) request.getParameter("start")
					.trim());
			double floatPageNum = start / 10;
			int intPageNum = (int) Math.ceil(floatPageNum);
			listFeedbackInfo.setCurrentPage(intPageNum + 1);
			session.setAttribute(LIST_INFO, listFeedbackInfo);
		}

		// call update and delete ....
		if (request.getParameter("delData") != null) {
			// user want to archive those type...
			String jsonString = request.getParameter("delData");
			deleteFeedbacks(jsonString);
		}

		// call service to get result
		BaseSearchResult searchResult = feedbackService
				.getList(listFeedbackInfo);

		// create json object and return back ...call DB get latest information
		// create JSON response
		FeedbackUtil.jsonResponse(searchResult, request, response);

		return null;
	}

	/**
	 * load data by id now. And return JSON data result to response
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView loadData(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		// get id first
		String feedbackId = (String) request.getParameter("id").trim();
		Feedback feedback = feedbackService.getFeedback(new Long(feedbackId));

		// push data back to Ajax page
		JsonMVCUtil.jsonFormalResponse(feedback.toJSONObject(), request,
				response);

		return null;
	}

	/**
	 * create health
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView createFeedback(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			Feedback feedback = new Feedback();
			FeedbackUtil.setFeedback(request, feedback);

			feedback.setCreationDate(new Date());
			feedback.setUpdateDate(new Date());
			boolean result = feedbackService.createFeedback(feedback);

			if (result) {
				// check to see whether parentId > 0 - add comments
				if (feedback.getParentId().intValue() > 0) {
					Feedback parentFeedback = feedbackService
							.getFeedback(feedback.getParentId());
					parentFeedback.setUpdateDate(new Date());
					parentFeedback
							.setComments(parentFeedback.getComments() + 1);
					feedbackService.createFeedback(parentFeedback);
				}

				JsonMVCUtil.jsonOkResponse(
						"You have successfully created this feedback", request,
						response);
			} else {
				JsonMVCUtil.jsonFailResponse(
						"Internal Error, please try again", request, response);
			}

		} catch (Exception e) {
			log.error("saveFeedback failed");
			JsonMVCUtil.jsonFailResponse("Internal Error, please try again",
					request, response);
		}

		return null;
	}

	/**
	 * Edit feedback now
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	public ModelAndView editFeedback(HttpServletRequest request,
			HttpServletResponse response) throws Exception {

		try {
			String id = (String) request.getParameter("id").trim();
			Feedback feedback = feedbackService.getFeedback(new Long(id));
			String origEmail = feedback.getEmail();

			FeedbackUtil.setFeedback(request, feedback);
			feedback.setUpdateDate(new Date());

			// now start to check email is match or not
			String enterEmail = (String) request.getParameter("email").trim();
			if (origEmail.equalsIgnoreCase(enterEmail)) {
				feedbackService.createFeedback(feedback);

				// check to see whether parentId > 0 - update comments
				if (feedback.getParentId().intValue() > 0) {
					Feedback parentFeedback = feedbackService
							.getFeedback(feedback.getParentId());
					parentFeedback.setUpdateDate(new Date());
					feedbackService.createFeedback(parentFeedback);
				}

				JsonMVCUtil.jsonOkResponse(
						"You have successfully updated this feedback", request,
						response);
			} else {
				JsonMVCUtil
						.jsonFailResponse(
								"Email address not match, you do not have permission to edit this item.",
								request, response);
			}

		} catch (Exception e) {
			JsonMVCUtil.jsonFailResponse("Internal Error, please try again",
					request, response);
		}

		return null;
	}

	/**
	 * client click delete account in here
	 * 
	 * @param jsonString
	 * @throws Exception
	 */
	private void deleteFeedbacks(String jsonString) throws Exception {
		JSONArray jsonArray = JsonUtil.getJsonArray(jsonString);

		// loop through - get from json and update
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonObject = jsonArray.getJSONObject(i);
			String id = jsonObject.getString("id");
			feedbackService.archiveFeedback(new Long(id));
		}
	}

	// spring inject
	public void setFeedbackService(FeedbackServiceImpl feedbackService) {
		this.feedbackService = feedbackService;
	}

}
